package com.ever.chatbot.api.domain.ai.service;

import com.alibaba.fastjson.JSON;
import com.ever.chatbot.api.domain.ai.IOpenAI;
import com.ever.chatbot.api.domain.ai.model.aggregates.AIAnswer;
import com.ever.chatbot.api.domain.ai.model.vo.AIResults;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
@Service
public class OpenAI implements IOpenAI {
    private Logger logger = LoggerFactory.getLogger(OpenAI.class);

    @Value("${chatbot-api.key}")
    private String key;

    @Override
    public String doJuHe(String question) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get =new HttpGet("http://web.juhe.cn/constellation/getAll?consName="+question+"&type=today&key="+key);
        get.addHeader("Content-Type","application/x-www-form-urlencoded");
        CloseableHttpResponse response = httpClient.execute(get);

        if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            String jsonStr = EntityUtils.toString(response.getEntity());
            AIAnswer aiAnswer = new AIAnswer();
            aiAnswer.setAiResults(JSON.parseObject(jsonStr, AIResults.class));
            return aiAnswer.getAiResults().toString();
        } else {
            throw new RuntimeException("api.openai.com Err Code is " + response.getStatusLine().getStatusCode());
        }
    }
}
